<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2021/5/24 0024
 * Time: 下午 3:25
 */
namespace app\model;
class UserMessage extends \think\Model{
    public $table="user_message";

    /**
     * @param $user_id 发送信息用户ID
     * @param $user_id2 接受信息用户ID
     * @param $content 发送内容
     */
    function add_message($user_id,$user_id2,$content){
        $data2['user_id']=$user_id;
        $data2['user_id2']=$user_id2;
        $data2['content']=$content;
        $data2['created_at']=cur_time();

        $arr=[$user_id,$user_id2];
        sort($arr);

        $data2['user_key']=implode(',',$arr);

        return $this->insert($data2,false,true);
    }

    /**
     * 根据用户ID，接受用户ID,返回他两人的对话记录
     * @param $user_id
     * @param $user_id2
     * @return mixed
     */
    function get_all_message_by_user_id_user_id2($user_id,$user_id2){
        $arr=[$user_id,$user_id2];
        sort($arr);
        $user_key=implode(',',$arr);
        $o=$this->where(["user_key"=>$user_key])->order("id","asc")->select();

        $arrs=object2array($o);
        $UserResume=new UserResume();
        foreach($arrs as $k=>$v){
            $arrs[$k]['user_id_arr']=$UserResume->get_head_img_name_by_user_id($v['user_id']);
            $arrs[$k]['user_id2_arr']=$UserResume->get_head_img_name_by_user_id($v['user_id2']);
        }
        return $arrs;
    }


    /**
     * 取得最近的消息聊天用户列表
     * @param $user_id
     */
    function get_recent_user($user_id){
        $arrs=$this->where("FIND_IN_SET('{$user_id}',user_key)")->order("id","desc")->group("user_key")->field("created_at,user_id,user_id2,user_key,max(id) as id")->select();
        //var_dump($this->getLastSql());
        $arr2=object2array($arrs);
        //var_dump($arr2);
        //var_dump('user_id:'.$user_id);
        foreach($arr2 as $k=>$v){
            if($user_id==$v['user_id']){
                $arr2[$k]['c_user_id']=$v['user_id2'];
            }else{
                $arr2[$k]['c_user_id']=$v['user_id'];
            }
            unset($arr2[$k]['user_id']);
            unset($arr2[$k]['user_id2']);

        }
        //var_dump($arr2);

        $UserModel=new User();
        $UserCompanyModel=new UserCompany();
        foreach($arr2 as $k=>$v){
            $u_c_arr=$UserCompanyModel->get_user_company($v['c_user_id']);
            $link_name=$u_c_arr['link_name'];
            $link_position=$u_c_arr['link_position'];
            $arr2[$k]['link_position']=$link_position?$link_position:'未知';
            $arr2[$k]['content']=$this->where(['id'=>$v['id']])->value("content");
        }
        return $arr2;

    }
}